<?php

namespace app\common\util;

use think\Response;

trait ApiResponseTrait
{
    // 定义常用的状态码常量
    const STATUS_OK = 200; // 成功
    const STATUS_BAD_REQUEST = 400;
    const STATUS_UNAUTHORIZED = 401;
    const STATUS_NOT_FOUND = 404;
    const STATUS_UNPROCESSABLE_ENTITY = 422;

    /**
     * 成功响应.
     *
     * @param mixed $data
     * @param int $status
     * @param array $headers
     * @param int $options
     * @param array $extraData
     * @return Response
     */
    public function success($data = [], int $status = self::STATUS_OK, array $headers = [], $options = JSON_UNESCAPED_UNICODE, array $extraData = []): Response
    {
        $response = [
            'code' => $status,
            'message' => '操作成功',
            'data' => $data,
        ];

        // 合并额外的数据
        $response = array_merge($response, $extraData);

        return Response::create($response, 'json', $status, $headers, $options);
    }

    /**
     * 错误响应.
     *
     * @param string $message
     * @param int $status
     * @param array $headers
     * @param int $options
     * @param array $extraData
     * @return Response
     */
    public function error(string $message = '发生错误', int $status = self::STATUS_BAD_REQUEST, array $headers = [], $options = JSON_UNESCAPED_UNICODE, array $extraData = []): Response
    {
        $response = [
            'code' => $status,
            'message' => $message,
        ];

        // 合并额外的数据
        $response = array_merge($response, $extraData);

        return Response::create($response, 'json', $status, $headers, $options);
    }

    /**
     * 未找到资源的响应.
     *
     * @param string $message
     * @param array $headers
     * @param int $options
     * @param array $extraData
     * @return Response
     */
    public function notFound(string $message = '资源未找到', array $headers = [], $options = JSON_UNESCAPED_UNICODE, array $extraData = []): Response
    {
        return $this->error($message, self::STATUS_NOT_FOUND, $headers, $options, $extraData);
    }

    /**
     * 未经授权的响应.
     *
     * @param string $message
     * @param array $headers
     * @param int $options
     * @param array $extraData
     * @return Response
     */
    public function unauthorized(string $message = '未授权', array $headers = [], $options = JSON_UNESCAPED_UNICODE, array $extraData = []): Response
    {
        return $this->error($message, self::STATUS_UNAUTHORIZED, $headers, $options, $extraData);
    }

    /**
     * 未经过验证的响应.
     *
     * @param string $message
     * @param array $headers
     * @param int $options
     * @param array $extraData
     * @return Response
     */
    public function notValidate(string $message = '验证失败', array $headers = [], $options = JSON_UNESCAPED_UNICODE, array $extraData = []): Response
    {
        return $this->error($message, self::STATUS_UNPROCESSABLE_ENTITY, $headers, $options, $extraData);
    }
}